package war2100.game.states;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import TWLSlick.BasicTWLGameState;

import war2100.Game;
import war2100.game.states.menu.BackToMainMenuHandler;
import war2100.game.states.menu.MenuButton;
import war2100.game.states.menu.StartGameHandler;

public class LobbyState extends BasicGameState {

	MenuButton startGame;
	MenuButton backToMainMenuButton;

	private DatagramSocket serverSocket;
	private byte[] receiveData;
	private byte[] sendData;
	
	public static final int ID = 1;

	@Override
	public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
		if (sbg instanceof Game) {
			Game game = (Game) sbg;
			
			startGame = new MenuButton(gc, gc.getWidth() - 170, gc.getHeight() - 90, 150, 30, "Starten", new StartGameHandler(game));
			backToMainMenuButton = new MenuButton(gc, gc.getWidth() - 170, gc.getHeight() - 50, 150, 30, "Hauptmenü", new BackToMainMenuHandler(game));
		}

		/*try {
			serverSocket = new DatagramSocket(9876);
			receiveData = new byte[1024];
			sendData = new byte[1024];
		}
		catch (SocketException e) {
			e.printStackTrace();
			Logger.getLogger(MenuButton.class.getName()).log(Level.WARNING, "Es konnte kein Netzwerkserver aufgebaut werden.");
		}*/
	}

	@Override
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
		startGame.render(gc, g);
		backToMainMenuButton.render(gc, g);
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
		boolean clicked = gc.getInput().isMousePressed(Input.MOUSE_LEFT_BUTTON);
		
		startGame.update(gc, delta, clicked);
		backToMainMenuButton.update(gc, delta, clicked);

		/*try {
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
			serverSocket.receive(receivePacket);
			String sentence = new String(receivePacket.getData());
			System.out.println("RECEIVED: " + sentence);
			InetAddress IPAddress = receivePacket.getAddress();
			int port = receivePacket.getPort();
			String capitalizedSentence = sentence.toUpperCase();
			sendData = capitalizedSentence.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
			serverSocket.send(sendPacket);
		}
		catch (IOException e) {
			e.printStackTrace();
		}*/
	}

	@Override
	public int getID() {
		return ID;
	}

}
